<?php
require_once('TVB/pms/pdes/action/ProgrammeGetAction.class.php');

class ProgrammeUpdateAction extends BaseAction 
{
	public $id;
	/**
	 * @isnull false
	 * @filter string_number
	 * @maxLength 255
	 * @label Programme Path
	 */
	public $path;
	public $cpl_category_id;
	public $parent_cpl_category;
	public $series_id;
	/**
	 * @filter number
	 * @maxLength 9
	 * @label No. of Episodes
	 */
	public $number_of_episodes;

// bug 3978    
//	/**
//	 * @filter number
//	 * @maxLength 9
//	 * @label Nominal Duration
//	 */
//	public $nominal_duration;

	/**
	 * @filter number
	 * @maxLength 9
	 * @label Starting Episode No.
	 */
	public $starting_original_episode_no;

// bug 3978    
//	/**
//	 * @filter date
//	 * @label Production Start Date
//	 */
//	public $production_start_date;
//	/**
//	 * @filter date
//	 * @label Production End Date
//	 */
//	public $production_end_date;

	public $first_network_codes;
	/**
	 * @filter datetime
	 * @label First Air Date/Time
	 */
	public $first_time_onair;

// bug 3978    
	/**
	 * @maxLength 255
	 * @label First Onair Information
	 */
	public $first_onair_information;

	/**
	 * @filter datetime
	 * @label First Episode Air DateTime
	 */
	public $first_episode_time_onair;
	/**
	 * @filter datetime
	 * @label Last Episode Air DateTime
	 */
	public $last_episode_time_onair;
	/**
	 * @filter datetime
	 * @label Publish Date/Time 
	 */
	public $publish_datetime;
	/**
	 * @filter datetime
	 * @label Expiry Date/Time
	 */
	public $expire_datetime;
	public $meta_keywords;
	public $meta_description;
	/**
	 * @maxLength 255
	 * @label Minisite Url
	 */
	public $minisite_url;
	/**
	 * @maxLength 255
	 * @label Blog Url
	 */
	public $blog_url;
	/**
	 * @filter number
	 * @maxLength 9
	 * @label Forum ID
	 */
	public $forum_id;

// bug 3978
//	/**
//	 * @filter number
//	 * @maxLength 9
//	 * @label Average Rating
//     */
//	public $average_rating;

	public $highlighted_cast_roles;
	public $casts;
	public $available_tag_types;
	public $tags;
	#public $folders;
    public $premium_flag;
    public $auto_publish;
    /**
     * @filter datetime
     * @label Auto Publish::Online Date Time
     */
	public $auto_publish_start_datetime;
    /**
     * @filter datetime
     * @label Auto Publish::Offline Date Time
     */
	public $auto_publish_end_datetime;
	public $status;
	public $created_at;
	public $created_by;
	public $modified_at;
	public $modified_by;
	public $priority;

	public $language_id;
	/**
	 * @maxLength 255
	 * @label chinese title
	 */
	public $title;
	public $settop_box_name;
	public $description;
	public $description_short;

	//public $fact_background; // bug 3978
	//public $objective; // bug 3978

	public $effective_date;
	/**
	 * @maxLength 255
	 * @label Programme No.
	 */
	public $cpl_id;
	public $cpl_company_code;

	public $category_id;
	/**
	 * @isnull false
	 * @label Programme.TVB.COM Category
	 */
	public $tvbcom_cat_id;
	public $tag;
	public $new_tag;

	//public $role_id;
	public $cast_id;
	public $name_type;
	public $name_last;
	public $name_first;
	public $alphabet;
	/**
	 * @maxLength 255
	 * @label english title
	 */
	public $title_en;
	public $param_role_id;
	public $param_cast_id;
	public $param_name_type;
	public $param_last_name;
	public $param_first_name;
	public $param_alphabet;

	public $ut;
	public $vid;
	public $reset;
	public $from;
	public $act;

    public $is_folder_update;

    //for table programme_subscription
    public $subscription_country_allow_deny;
    public $subscription_country;

    /**
     * @filter datetime
     * @label Online Date Time
     */
    public $subscription_publish_datetime;
    /**
     * @filter datetime
     * @label Offline Date Time
     */
    public $subscription_expire_datetime;
    public $subscription_free;

    //bug 3688
    public $folder_video_id;
    public $folder_video_act;

    // for table programme_premium
    public $premium_title_en;
    public $premium_title;
    public $premium_auto_publish;
    public $premium_items;
    
    //for table programme_ppv
    public $ppv_country;
    public $ppv_country_allow_deny;
    
    /**
     * @filter datetime
     * @label Online Date Time
     */
    public $ppv_publish_datetime;
    /**
     * @filter datetime
     * @label Online Date Time
     */
    public $ppv_expire_datetime;

    public $video_type;
    public function execute()
    {
		if (!is_null($this->reset))
		{
			$this->setData('id', $this->id);
			$this->setData('act', $this->act);
			$this->setData('step', 2);
			$this->setData('from', $this->from);
			return 'reset';
		}

		Model::$dbo['w']->beginTransaction();
		try{
            // bug 6373
			if (!empty($this->premium_items)) {
				$this->premium_flag = TRUE;
            }
            
			if (CommonUtils::is_concurrent('programme', $this->id, $this->modified_at))
			{
				$this->addError('concurrent', array('0105', 'Concurrent update found!'));
				$this->init_page_data();
				return 'logic-error';
			}

			if (count($this->_errors) > 0)
			{
				$this->init_page_data();
				return "filter-error";
			}

			//check name unique
			if (is_null($this->title) && is_null($this->title_en))
			{
				$this->addError('Programme.Programme Title', array('0037', 'Programme Title'));
				$this->init_page_data();
				return 'filter-error';
            }

			if ($this->check_effective_date())
			{
				$this->addError('Equivalent Programme. Effective Date', array('0054', 'Effective Date'));
				$this->init_page_data();
				return 'filter-error';
			}

			if (!is_null($this->first_episode_time_onair) && !is_null($this->last_episode_time_onair))
			{
				if ($this->first_episode_time_onair > $this->last_episode_time_onair)
                {
                    $this->addError('First Episode On Air Date Time && Last Episode On Air Date Time', 
									array('0050', 'First Episode On Air Date Time && Last Episode On Air Date Time'));
					$this->init_page_data();
					return 'filter-error';
				}
			}

			if (!is_null($this->expire_datetime))
			{
				if ($this->publish_datetime > $this->expire_datetime)
				{
 					$this->addError('Publish Date/Time && Expiry Date/Time', 
									array('0033', 'Publish Date/Time && Expiry Date/Time'));
					$this->init_page_data();
					return 'filter-error';
				}
			}

            if ($this->_checkFirstAirDatetime() == FALSE) {
  			    $this->addError('First Air Date/Time', array('0206', 'First Air Date/Time'));
                $this->init_page_data();
                return 'filter-error';
            }

			if ($this->__checkAutoPublishTime() === FALSE) {
				return 'filter-error';
			}
			/*{{{*/

// bug 3978
//			if ($this->production_start_date) {
//				if ($this->production_start_date > $this->production_end_date) {
//					$this->addError('Production Period', array('0056', 'Production Period'));
//					$this->init_page_data();
//					return 'filter-error';
//				}
//			}

            //for bug 4034
			$matchmis_data = programme_cpl::checkCplInMis($this->id);
            $flag = true;
            $cpl_data = array();
            if(!empty($matchmis_data))
            {
                $tmp = array();
                foreach($matchmis_data as $data)
                {
                    $num = count($this->cpl_id);
                    if($num == 0)
                    {
                        $flag = false;
                        $cpl_data[] = $data['cpl_company_code'].' '.$data['cpl_id'].' '.date('Y-m-d',strtotime($data['effective_date']));
                    }

                    for ($i=0; $i<$num; $i++)
                    {
                        if($this->cpl_id[$i] == $data['cpl_id'] && $this->cpl_company_code[$i] == $data['cpl_company_code'])
                        {
                            $tmp[] = true;
                        }
                        else
                        {
                            $tmp[] = false;
                            $cpl_data[] = $data['cpl_company_code'].' '.$data['cpl_id'].' '.date('Y-m-d',strtotime($data['effective_date']));
                        }
                    }	
                }
                $t = strstr(implode('',$tmp),'1');
                $flag = empty($t) ? false : true;
                $cpl_data = array_unique($cpl_data);
            }

            if(!$flag)
            {
				$this->addError('Cpl & CO_CODE', array('0300','Equivalent Programme '.implode(', ',$cpl_data)));
                $this->init_page_data();
				return 'logic-error';
            }
			//check path repeat
			$check_programme_id = programme::checkPath($this->path);
			if ($check_programme_id && $check_programme_id != $this->id)
			{
				$this->addError('path', array('0100','path:'.$this->path));
				$this->init_page_data();
				return 'logic-error';
            }

            //check premium title unique
			if ($this->premium_flag)
            {
                if(is_null($this->premium_title_en) && is_null($this->premium_title))
                {
                    $this->addError('Programme.Programme Title', array('0037', 'Programme Premium Title'));
                    $this->init_page_data();
                    return 'filter-error';
                }
            }

			# bug 6373
			/*
            if($this->premium_flag && empty($this->premium_items))
            {
                $this->addError('Premium Items', array('0401', 'Premium Items'));
                $this->init_page_data();
                return 'filter-error';
            }
			 */

            if($this->premium_flag && !empty($this->premium_items) && in_array('subscription',$this->premium_items))
            {
                if ($this->__check_subscription_datetime() == FALSE) {
                    $this->init_page_data();
                    return 'filter-error';
                }
            }

            if($this->premium_flag && !empty($this->premium_items) && in_array('ppv',$this->premium_items))
            {
                if ($this->__check_ppv_datetime() == FALSE) {
                    $this->init_page_data();
                    return 'filter-error';
                }
            }

			# bug 7113
			if ($this->cpl_id && $this->cpl_company_code && $this->effective_date){
				foreach($this->cpl_id as $index=>$cpl_id){
					$_p_id = programme_cpl::checkCpl($cpl_id, $this->cpl_company_code[$index]);
					if($_p_id && $_p_id != $this->id){
						$this->addError('Programme No & Company Code',array('0104', 'Equivalent Programme'));
						$this->init_page_data();
						return 'logic-error';
					}
				}
			}

			# change_log
			$this->change_log   = array();
			$this->programme_id = $this->id;
			$this->episode_id   = array();

			//bug:7302      /*modified by Albie Lu on 2011-10-10 */
            $programme_premium = new programme_premium;
		    $premium = $programme_premium->get($this->id);
            if(empty($this->premium_flag) && !empty($premium))
            {
                $this->deleteVideoPremium($this->id);
				# change_log add
            }

            $this->update_programme_premium();
            $this->update_programme_subscription();
            $this->update_programme_ppv();
       
			$cast_id = $this->handle_cast_main();
			$this->update_programme($cast_id);
			$this->update_programme_language();
			$this->update_multiple_language();

			$this->change_log[] = array(
				'type' => 'programme',
				'keys' => array('id'=>$this->id),
				'is_active' => 1,
				'is_publish'=> 0,
				'programme_id'=>$this->id,
			);
			$this->change_log[] = array(
				'type' => 'programme-language',
				'keys' => array('programme_id'=>$this->id,'language_id'=>language::getLanguageID(AC::LANGUAGE_ZH)),
				'is_active' => 1,
				'is_publish'=> 0,
				'programme_id'=>$this->id,
			);
			$this->change_log[] = array(
				'type' => 'programme-language',
				'keys' => array('programme_id'=>$this->id,'language_id'=>language::getLanguageID(AC::LANGUAGE_EN)),
				'is_active' => 1,
				'is_publish'=> 0,
				'programme_id'=>$this->id,
			);

			$this->update_tvb_category($this->id);
            $this->update_cpl($this->id);
            
            $primary_key = array(
                'programme_id'  => $this->id
            );
            $fields = array(
                'title', 
                'first_onair_information', 
                'settop_box_name', 
                'description', 
                'description_short', 
                'fact_background', 
                'objective'
            );
            CommonUtils::filterC2A0('programme-language', $primary_key, $fields);

			array_walk($this->change_log,'change_log::updateOne');

			Model::$dbo['w']->commit();

            if ($this->folder_video_id) {
                $this->setData('id', $this->folder_video_id);
			    $this->setData('type', 'video');
			    $this->setData('act', $this->folder_video_act);
				$this->setData('from', 'programme');
				return 'video';
            } 
            else if ($this->is_folder_update)
            {
                $this->setData('act', $this->act);
                $this->setData('step', '2');
                $this->setData('id', $this->id);

                return 'folder';
            }
            else if (is_null($this->param_cast_id) && is_null($this->vid))
			{
				if ($this->from == 'task')
				{
					return 'task';
				}
				$this->setData('type', 'programme');
				return 'succ';
			}
			elseif ($this->vid)
			{
			    $this->setData('id', $this->vid);
			    $this->setData('type', 'video');
			    $this->setData('act', 'edit');
				$this->setData('from', 'programme');
				return 'video';
			}
			else
			{
				$act = ($this->param_cast_id < 0) ? "add" : "edit";
				$this->setData('id', $cast_id);
				$this->setData('act', $act);
				$this->setData('from', 'programme');
				$this->setData('programme_id', $this->id);
				$this->setData('step', 2);
				return 'cast';
			}
		}
		catch(Exception $e)
		{
			error_log("Update programme Fails: {$this->id}" . var_export($e, 1));
			error_log("Request: " . var_export($this, 1));

			Model::$dbo['w']->rollBack();

			return 'system-error';
		}
	}    

	private function update_programme($cast_id)
	{
		$programme = new programme();
		$programme = $programme->get($this->id);
		Model::diff($programme, $this);
		$programme->modified_at = date("Y-m-d H:i:s");
		$programme->modified_by = CommonUtils::get_user();
		$programme->tags = $this->add_tag();
		$programme->first_network_codes = ($this->first_network_codes) ? implode(",", $this->first_network_codes) : '';
		//bug 3978        
		//$programme->nominal_duration = $this->add_nominal_duration();
		$programme->cpl_category_id  = is_null($this->cpl_category_id) ? $this->parent_cpl_category : $this->cpl_category_id;
		$programme->casts = $this->add_cast_field($cast_id);
		$programme->path = strtolower(trim($this->path));
		$programme->blog_url = trim($this->blog_url);
		$programme->forum_id = trim($this->forum_id);
		$programme->minisite_url = trim($this->minisite_url);
		$programme->publish_datetime = $this->publish_datetime;
		$programme->expire_datetime = $this->expire_datetime;
		$programme->auto_publish_starttime = $programme->auto_publish ? $this->auto_publish_start_datetime : '';
		$programme->auto_publish_endtime = $programme->auto_publish ? $this->auto_publish_end_datetime : '';

		$update_id = Model::$dbo['w']->save($programme);
		if($update_id>0) {
            $primary_key = array(
                'id'  => $this->id
            );
            $fields = array(
                'path', 
                'meta_keywords', 
                'meta_description', 
                'minisite_url', 
                'blog_url',
                'casts', 
                'available_tag_types', 
                'tags', 
                'folders',
            );
            $ret = CommonUtils::filterC2A0('programme', $primary_key, $fields);

			$this->addInfo("programme:".AC::LOG_OP_UPDATE.":".$this->id, "update programme success", json_encode($programme));
		} else {
			$this->addError("programme:".AC::LOG_OP_UPDATE.":".$this->id, "update programme failed", json_encode($programme));
		}
	}
      
	/**
	 * update programme language
	 */
	private function update_programme_language()
    {
		$programme_language = new programme_language();	
		$programme_language = $programme_language->getLangProgrammeByID($this->id, language::getLanguageID(AC::DEFAULT_LANGUAGE));
		Model::diff($programme_language, $this);
		$programme_language->title = is_null($this->title) ? "" : trim($this->title);
        $programme_language->description = is_null($this->description[$programme_language->language_id]) ? "" : $this->description[$programme_language->language_id];
        $programme_language->description_short = is_null($this->description_short[$programme_language->language_id]) ? "" : $this->description_short[$programme_language->language_id];
// bug 3978        
    $programme_language->first_onair_information = is_null($this->first_onair_information[$programme_language->language_id]) ? "" : trim($this->first_onair_information[$programme_language->language_id]);
		$update_id = Model::$dbo['w']->save_by_fields($programme_language, array('programme_id','language_id'));
		if ($update_id)
		{
			$this->addInfo("programme-language:".AC::LOG_OP_UPDATE.":".$this->id, "update programme language success", json_encode($programme_language));
		}
		else
		{
			$this->addError("programme-language:".AC::LOG_OP_UPDATE.":".$this->id, "update programme language failed", json_encode($programme_language));
		}
	}
	/**
	 * update multiple language programme
	 */
	private function update_multiple_language()
	{
		$programme_language = new programme_language();	
		$programme_language = $programme_language->getLangProgrammeByID($this->id, language::getLanguageID(AC::LANGUAGE_EN));
		$programme_language->title = is_null($this->title_en) ? "" : trim($this->title_en);
        $programme_language->description = is_null($this->description[$programme_language->language_id]) ? "" : $this->description[$programme_language->language_id];
        $programme_language->description_short = is_null($this->description_short[$programme_language->language_id]) ? "" : $this->description_short[$programme_language->language_id];
// bug 3978        
     $programme_language->first_onair_information = is_null($this->first_onair_information[$programme_language->language_id]) ? "" : trim($this->first_onair_information[$programme_language->language_id]);
		$update_id = Model::$dbo['w']->save_by_fields($programme_language, array('programme_id','language_id'));
		if ($update_id)
        {
			$this->addInfo("programme-language:".AC::LOG_OP_UPDATE.":".$this->id, "update programme en language success", json_encode($programme_language));
		}
		else
		{
			$this->addError("programme-language:".AC::LOG_OP_UPDATE.":".$this->id, "update programme en language failed", json_encode($programme_language));
		}
	}

	private function update_cpl($programme_id)
	{
		# change_log del
		$old_data = CommonUtils::exec_sql(Model::$dbo['w']->getDbHandle(),'select * from programme_cpl where programme_id='.$programme_id);
		foreach($old_data as $row){
			$this->change_log[] = array(
				'type' => 'programme_cpl',
				'keys' => array('programme_id'=>$programme_id,'effective_date'=>$row['effective_date']),
				'is_active' => 0,
				'is_publish'=> 0,
				'programme_id'=>$programme_id,
			);
		}

		$programme_cpl = new programme_cpl();
		$programme_cpl->delBySql($programme_id);

		if ($this->cpl_id && $this->cpl_company_code && $this->effective_date)
		{
			$num = count($this->cpl_id);
			for ($i=0; $i<$num; $i++)
			{
				$programme_cpl->programme_id = $programme_id;
				$programme_cpl->cpl_id = urldecode(trim($this->cpl_id[$i]));
				$programme_cpl->cpl_company_code = $this->cpl_company_code[$i];
				$programme_cpl->effective_date = $this->effective_date[$i].' 00:00:00';
				
				$ret = Model::$dbo['w']->save($programme_cpl);
				if ($ret >= 0)
				{
					$this->addInfo("programme_cpl:".AC::LOG_OP_UPDATE.":".$programme_id, "update programme cpl success", json_encode($programme_cpl));

					# change_log add
					$this->change_log[] = array(
						'type' => 'programme_cpl',
						'keys' => array('programme_id'=>$programme_id,'effective_date'=>$programme_cpl->effective_date),
						'is_active' => 1,
						'is_publish'=> 0,
						'programme_id'=>$programme_id,
					);
				} else {
					$this->addError("programme_cpl:".AC::LOG_OP_UPDATE.":".$programme_id, "update programme cpl failed", json_encode($programme_cpl));
				}
			}
		}
	}


    private function update_programme_premium()
    {
        $programme_premium = new programme_premium;
        $premium = $programme_premium->get($this->id);
        if(empty($this->premium_flag))
        {
            $this->premium_title_en = '';
            $this->premium_title = '';
            $this->premium_auto_publish = 0;
            $this->premium_items = '';
            if(!empty($premium))
            {
                $programme_premium->delete($this->id);
				$this->change_log[] = array(
					'type'=>'programme_premium',
					'keys'=>array('programme_id'=>$this->id),
					'is_active' => 0,
					'is_publish'=> 0,
					'programme_id'=>$this->id,
				);
            }
            return;
        }

        if (empty($premium)) {
            $programme_premium->set($this);
            $rs = $programme_premium->insert($programme_premium);
            if (mysql_error()) {
                $this->addError("programme_premium:".AC::LOG_OP_CREATE.":".$this->id, "update programme premium failed", json_encode($programme_premium));
            } else {
				$this->change_log[] = array(
					'type'=>'programme_premium',
					'keys'=>array('programme_id'=>$this->id),
					'is_active' => 1,
					'is_publish'=> 0,
					'programme_id'=>$this->id,
				);
                $this->addInfo("programme_premium:".AC::LOG_OP_CREATE.":".$this->id, "update programme premium success", json_encode($programme_premium));
            }
        } else {
            $programme_premium->set($this);
            Model::diff($premium, $programme_premium);
            $rs = $programme_premium->update($premium);
            if ($rs) {
				$this->change_log[] = array(
					'type'=>'programme_premium',
					'keys'=>array('programme_id'=>$this->id),
					'is_active' => 1,
					'is_publish'=> 0,
					'programme_id'=>$this->id,
				);
                $this->addInfo("programme_premium:".AC::LOG_OP_UPDATE.":".$this->id, "update programme premium success", json_encode($premium));
            } else {
                $this->addError("programme_premium:".AC::LOG_OP_UPDATE.":".$this->id, "update programme premium failed", json_encode($premium));
            }
        }
    }

    private function update_programme_ppv()
    {
        $programme_ppv = new programme_ppv;
        $ppv = $programme_ppv->get($this->id);
        if(empty($this->premium_flag) || empty($this->premium_items) || !in_array('ppv',$this->premium_items))
        {
            $this->ppv_country_allow_deny = '';
            $this->ppv_country = '';
            $this->ppv_publish_datetime = '';
            $this->ppv_expire_datetime = '';
            if(!empty($ppv))
            {
                $programme_ppv->delete($this->id);
				$this->change_log[] = array(
					'type'=>'programme_ppv',
					'keys'=>array('programme_id'=>$this->id),
					'is_active' => 0,
					'is_publish'=> 0,
					'programme_id'=>$this->id,
				);
            }
            return;
        }

        if (empty($ppv)) {
            $programme_ppv->set($this);
            $rs = $programme_ppv->insert($programme_ppv);
            if (mysql_error()) {
                $this->addError("programme_ppv:".AC::LOG_OP_CREATE.":".$this->id, "update programme pay per view failed", json_encode($programme_ppv));
            } else {
				$this->change_log[] = array(
					'type'=>'programme_ppv',
					'keys'=>array('programme_id'=>$this->id),
					'is_active' => 1,
					'is_publish'=> 0,
					'programme_id'=>$this->id,
				);
                $this->addInfo("programme_ppv:".AC::LOG_OP_CREATE.":".$this->id, "update programme pay per view success", json_encode($programme_ppv));
            }
        } else {
            $programme_ppv->set($this);
            Model::diff($ppv, $programme_ppv);
            $rs = $programme_ppv->update($ppv);
            if ($rs) {
				$this->change_log[] = array(
					'type'=>'programme_ppv',
					'keys'=>array('programme_id'=>$this->id),
					'is_active' => 1,
					'is_publish'=> 0,
					'programme_id'=>$this->id,
				);
                $this->addInfo("programme_ppv:".AC::LOG_OP_UPDATE.":".$this->id, "update programme pay per view success", json_encode($ppv));
            } else {
                $this->addError("programme_ppv:".AC::LOG_OP_UPDATE.":".$this->id, "update programme pay per view failed", json_encode($ppv));
            }
        }
       
    }
    private function update_programme_subscription()
    {
        $programme_subscription = new programme_subscription;
        $subscription = $programme_subscription->get($this->id);
        if(empty($this->premium_flag) || empty($this->premium_items) || !in_array('subscription',$this->premium_items))
        {
            $this->subscription_country_allow_deny = '';
            $this->subscription_country = '';
            $this->subscription_free = 0;
            $this->subscription_publish_datetime = '';
            $this->subscription_expire_datetime ='';
            if(!empty($subscription))
            {
                $programme_subscription->delete($this->id);
				$this->change_log[] = array(
					'type'=>'programme_subscription',
					'keys'=>array('programme_id'=>$this->id),
					'is_active' => 0,
					'is_publish'=> 0,
					'programme_id'=>$this->id,
				);
            }
            return;
        }

        if (empty($subscription)) {
            $programme_subscription->set($this);
            $rs = $programme_subscription->insert($programme_subscription);
            if (mysql_error()) {
                $this->addError("programme_subscription:".AC::LOG_OP_CREATE.":".$this->id, "update programme subscription failed", json_encode($programme_subscription));
            } else {
				$this->change_log[] = array(
					'type'=>'programme_subscription',
					'keys'=>array('programme_id'=>$this->id),
					'is_active' => 1,
					'is_publish'=> 0,
					'programme_id'=>$this->id,
				);
                $this->addInfo("programme_subscription:".AC::LOG_OP_CREATE.":".$this->id, "update programme subscription success", json_encode($programme_subscription));
            }
        } else {
            $programme_subscription->set($this);
            Model::diff($subscription, $programme_subscription);
            $rs = $programme_subscription->update($subscription);
            if ($rs) {
				$this->change_log[] = array(
					'type'=>'programme_subscription',
					'keys'=>array('programme_id'=>$this->id),
					'is_active' => 1,
					'is_publish'=> 0,
					'programme_id'=>$this->id,
				);
                $this->addInfo("programme_subscription:".AC::LOG_OP_UPDATE.":".$this->id, "update programme subscription success", json_encode($subscription));
            } else {
                $this->addError("programme_subscription:".AC::LOG_OP_UPDATE.":".$this->id, "update programme subscription failed", json_encode($subscription));
            }
        }
    }

	private function check_effective_date()
	{
		$flag = false;
		if ($this->cpl_id && $this->cpl_company_code && $this->effective_date)
		{
			$num = count($this->cpl_id);
			for($i=0; $i<$num; $i++)
			{
				$effective_date_arr[] = substr($this->effective_date[$i],0,10);
			}
			$arr_new = array_unique($effective_date_arr);
			$num_new = count($arr_new);

			if ($num != $num_new) 
			{
				$flag = true;
			}
		}
		return $flag;
	}

	/**
	 * add/update tvb category data
	 */
	private function update_tvb_category($programme_id)
	{
		# change_log del
		$old_data = CommonUtils::exec_sql(Model::$dbo['w']->getDbHandle(),'select * from `programme-tvbcom_category` where programme_id='.$programme_id);
		foreach($old_data as $row){
			$this->change_log[] = array(
				'type' => 'programme-tvbcom_category',
				'keys' => array('programme_id'=>$programme_id,'category_id'=>intval($row['category_id'])),
				'is_active' => 0,
				'is_publish'=> 0,
				'programme_id'=>$programme_id,
			);
		}

		$programme_tvbcom_category = new programme_tvbcom_category();		
		$programme_tvbcom_category->delBySql($programme_id);
		if (!empty($this->tvbcom_cat_id)) {
			$this->tvbcom_cat_id = array_unique($this->tvbcom_cat_id);
			foreach ($this->tvbcom_cat_id as $key=>$id)	{
				$programme_tvbcom_category->programme_id = $programme_id;
				$programme_tvbcom_category->category_id = $id;
                $programme_tvbcom_category->rank = $key+1;
				$ret = Model::$dbo['w']->save($programme_tvbcom_category);
				if ($ret >= 0) {
                    $this->addInfo("programme-tvbcom_category:".AC::LOG_OP_UPDATE.":".$programme_id, "update programme tvbcom category success", json_encode($programme_tvbcom_category));
					# change_log add
					$this->change_log[] = array(
						'type' => 'programme-tvbcom_category',
						'keys' => array('programme_id'=>$programme_id,'category_id'=>$id),
						'is_active' => 1,
						'is_publish'=> 0,
						'programme_id'=>$programme_id,
					);
				} else {
                    $this->addError("programme-tvbcom_category:".AC::LOG_OP_UPDATE.":".$programme_id, "update programme tvbcom category failed", json_encode($programme_tvbcom_category));
				}
			}
		}
	}

	/**
	 * add/update tag data
	 */
	private function add_tag()
	{
		$tag_arr = array();
		if (!empty($this->tag))
		{
			foreach ($this->tag as $tags)
			{
				foreach ($tags as $value)
				{
					$tag_arr[] = $value;
				}
			}
		}

		$tag = new tag();
		if (isset($this->new_tag) && !empty($this->new_tag))
		{
			foreach ($this->new_tag as $type=>$newtag)
			{
				foreach ($newtag as $name)
				{
					$tag->parent_id = 0;
					$tag->tag_type_id = $type;
					$tag->system_label = $name;
					$ret = Model::$dbo["w"]->save($tag);
					if ($ret >= 0)
					{
						$tag_arr[] = $ret;
						$this->addInfo("tag:".AC::LOG_OP_UPDATE.":".$ret, "update programme's tag success", json_encode($tag));
					}
					else
					{
						$this->addError("tag:".AC::LOG_OP_UPDATE.":".$ret, "update programme's tag failed", json_encode($tag));
					}
				}
			}
		}

		return implode(",", $tag_arr);
	}

// bug 3978
//	private function add_nominal_duration()
//	{
//		if ($this->nominal_duration[0] == '' && $this->nominal_duration[1] == '' && $this->nominal_duration[2] == '')
//		{
//			return null;
//		}
//		else
//		{
//			return $this->nominal_duration[0]*3600+$this->nominal_duration[1]*60+$this->nominal_duration[2];
//		}
//	}

	/**
	 * handle cast array
	 */
	/*
	private function add_cast_field($cast_id)
	{
		if ($cast_id > 0)
		{
			$new_cmp_array = array("role_id"=>$this->param_role_id, "name_type"=>$this->param_name_type,"last_name"=>$this->param_last_name,"first_name"=>$this->param_first_name,"alphabet"=>(int)$this->param_alphabet);
		}
		else
		{
			$new_cmp_array = false;
		}

		$cast_arr = array();
		$len = count($this->role_id);
		for ($i=0; $i<$len; $i++)
		{
			if (empty($this->name_first[$i])) continue;
		
			$role_id = $this->role_id[$i];
			$old_cmp_array = array("role_id"=>$this->role_id[$i], "name_type"=>$this->name_type[$i],"last_name"=>trim($this->name_last[$i]),"first_name"=>trim($this->name_first[$i]), "alphabet"=>$this->alphabet[$i]);
			
			if ($new_cmp_array)
			{
				$cmp_result = array_diff_assoc($new_cmp_array,$old_cmp_array);
				if (empty($cmp_result))
				{
					$cast_arr[$role_id][] = array("cast_id"=>$cast_id,"name_type"=>$this->name_type[$i], "last_name"=>trim($this->name_last[$i]),"first_name"=>trim($this->name_first[$i]), "alphabet"=>$this->alphabet[$i]);
				}
				else
				{
					$cast_arr[$role_id][] = array("cast_id"=>$this->cast_id[$i],"name_type"=>$this->name_type[$i],"last_name"=>trim($this->name_last[$i]),"first_name"=>trim($this->name_first[$i]), "alphabet"=>$this->alphabet[$i]);
				}
			}
			else
			{
				$cast_arr[$role_id][] = array("cast_id"=>$this->cast_id[$i],"name_type"=>$this->name_type[$i],"last_name"=>trim($this->name_last[$i]),"first_name"=>trim($this->name_first[$i]), "alphabet"=>$this->alphabet[$i]);
			}
		}

		return json_encode($cast_arr);
	}
	 */

	private function add_cast_field($cast_id)
	{
		if ($cast_id > 0) {
			$new_cmp_array = array(
				"role_id" => $this->param_role_id, 
				"name_type" => $this->param_name_type,
				"last_name" => $this->param_last_name,
				"first_name" => $this->param_first_name,
				"alphabet" => (int)$this->param_alphabet
			);
		} else {
			$new_cmp_array = false;
		}

		$cast_arr = array();

		// by donald.chen @ 2011-04-08
		if (!empty($this->name_type)) {
			foreach ($this->name_type as $role_id => $name_type_arr) {	
				foreach ($name_type_arr as $i => $name_type) {
					if (empty($this->name_first[$role_id][$i])) continue;
			
					$old_cmp_array = array(
						"role_id" => $role_id, 
						"name_type" => $this->name_type[$role_id][$i],
						"last_name" => trim($this->name_last[$role_id][$i]),
						"first_name" => trim($this->name_first[$role_id][$i]), 
						"alphabet" => $this->alphabet[$role_id][$i]
					);
				
					if ($new_cmp_array) {
						$cmp_result = array_diff_assoc($new_cmp_array,$old_cmp_array);
						if (empty($cmp_result)) {
							$cast_arr[$role_id][] = array(
								"cast_id" => $cast_id,
								"name_type" => $this->name_type[$role_id][$i], 
								"last_name" => trim($this->name_last[$role_id][$i]),
								"first_name" => trim($this->name_first[$role_id][$i]), 
								"alphabet" => $this->alphabet[$role_id][$i]
							);
						} else {
							$cast_arr[$role_id][] = array(
								"cast_id" => $this->cast_id[$role_id][$i],
								"name_type" => $this->name_type[$role_id][$i],
								"last_name" => trim($this->name_last[$role_id][$i]),
								"first_name" => trim($this->name_first[$role_id][$i]), 
								"alphabet" => $this->alphabet[$role_id][$i]
							);
						}
					} else {
						$cast_arr[$role_id][] = array(
							"cast_id" => $this->cast_id[$role_id][$i],
							"name_type" => $this->name_type[$role_id][$i],
							"last_name" => trim($this->name_last[$role_id][$i]),
							"first_name" => trim($this->name_first[$role_id][$i]), 
							"alphabet" => $this->alphabet[$role_id][$i]
						);
					}
				}
			}
		}

		return json_encode($cast_arr);
	}

	/**
	 * handle cast main
	 *
	 * @return int -1 : not operate cast info
	 * @return int >0 : add/modify cast
	 */
	private function handle_cast_main()
	{
		//add
		if ($this->param_cast_id < 0)
		{
			$cast_id = $this->handle_cast();
			if ($cast_id > 0)
			{
				$this->handle_cast_language($cast_id);
			}
			return $cast_id;
		}
		elseif($this->param_cast_id)
		{
			//modify
			//$cast_id = $this->handle_cast();
			//if (false != $cast_id)
			//{
				//$this->handle_cast_language($this->param_cast_id);
			//}
			return $this->param_cast_id;
		}

		return -1;
	}

	/**
	 * operation of cast
	 */
	private function handle_cast()
	{
		$cast = new cast();
		//modify
		if ($this->param_cast_id > 0)
		{
			/*
			$cast = $cast->get($this->param_cast_id);
			$cast->modified_at = date("Y-m-d H:i:s", $_SERVER['REQUEST_TIME']);
			$cast->modified_by = CommonUtils::get_user();
			 */
		}
		else
		{
			$cast->set($this);
			$cast->blog_url = '';
			$cast->created_at = date("Y-m-d H:i:s", $_SERVER['REQUEST_TIME']);
			$cast->created_by = CommonUtils::get_user();
			$cast->modified_at = date("Y-m-d H:i:s", $_SERVER['REQUEST_TIME']);
			$cast->modified_by = $cast->created_by;
			$cast->cast_role_id = $this->param_role_id;
			$cast->programme_id = $this->id;
			$cast->folders = CommonUtils::init_folder("cast", $this);
			$cast->available_tag_types = CommonUtils::get_allow_tags("cast");
			$cast->status = AC::STATUS_NEW;
		}
		

		$cast_id = Model::$dbo['w']->save($cast);
		if ($cast_id >= 0 )
		{
			$this->_log_episode_id = array();
			$this->_log_programme_id = $this->id;
			$this->change_log[] = array(
				'type' => 'cast',
				'keys' => array('id'=>$cast_id),
				'is_active' => 1,
				'is_publish'=> 0,
				'programme_id'=>$this->id,
			);
			$this->addInfo("cast:".AC::LOG_OP_CREATE.":".$cast_id, "add cast success", json_encode($cast));
			return ($this->param_cast_id > 0) ? true : $cast_id;
		}
		else
		{
			$this->addError("cast:".AC::LOG_OP_CREATE.":".$cast_id, "add cast failed", json_encode($cast));
			return false;
		}
	}

	/**
	 * handle cast language
	 */
	private function handle_cast_language($cast_id)
	{
		//$cast_language = new cast_language();
		//$cast_detail = $cast_language->getCastByID($cast_id);
		//record find
		//if ($cast_detail)
		//{
			/*
			$cast_language->delBySql($cast_id);
			$cast_language_detail = new cast_language();
			$cast_language_detail->set($cast_detail);
			 */
		//}
		//else
		//{
			$cast_language_detail = new cast_language();
		//}
		$cast_language_detail->set($this);
		$lang_code = ($this->param_alphabet == 1) ? AC::LANGUAGE_ZH : AC::LANGUAGE_EN;
		$cast_language_detail->language_id = language::getLanguageID($lang_code);

		$cast_language_detail->cast_id = $cast_id;
		if ($this->param_name_type == 1)
		{
			$cast_language_detail->real_first_name = is_null($this->param_first_name) ? '' : trim($this->param_first_name);
			$cast_language_detail->real_last_name = is_null($this->param_last_name) ? '' : trim($this->param_last_name);
		}
		elseif ($this->param_name_type == 2)
		{
			$cast_language_detail->first_name = trim($this->param_first_name);
			$cast_language_detail->last_name  = trim($this->param_last_name);
		}
		elseif ($this->param_name_type == 12)
		{
			$cast_language_detail->nickname = is_null($this->param_first_name) ? '' : trim($this->param_first_name);
		}
		elseif ($this->param_name_type == 11)
		{
			$cast_language_detail->other_name = trim($this->param_first_name);
		}
		$ret = Model::$dbo['w']->save($cast_language_detail);
		if ($ret >= 0)
		{
            $primary_key = array(
                'cast_id'   => $cast_id
            );
            $fields = array(
                'real_first_name', 
                'real_last_name', 
                'first_name', 
                'last_name', 
                'other_name', 
                'nickname', 
                'occupation', 
                'personality', 
                'profile', 
                'history'
            );
            CommonUtils::filterC2A0('cast-language', $primary_key, $fields);
			$this->change_log[] = array(
				'type' => 'cast-language',
				'keys' => array('cast_id'=>$cast_id,'language_id'=>$cast_language_detail->language_id),
				'is_active' => 1,
				'is_publish'=> 0,
				'programme_id'=>$this->id,
			);
			$this->addInfo("cast-language:".AC::LOG_OP_UPDATE.":".$cast_id, "update cast language success", json_encode($cast_language_detail));
		}
		else
		{
			$this->addError("cast-language:".AC::LOG_OP_UPDATE.":".$cast_id, "update cast language failed", json_encode($cast_language_detail));
		}
	}

	/**
	 * init page data
	 */
	private function init_page_data()
	{
		$action = new ProgrammeGetAction();
		$action->id = $this->id;
		$action->act = 'edit';
		$action->step = 2;
		$action->execute();

		$old_data = $action->getData();
		$this->modified_at = $old_data['programme']->modified_at;
		$new_data['programme'] = Model::diff($old_data['programme'], $this);
		//retain title
		$new_data['programme']->zh_programme_name = trim($this->title);
		$new_data['programme']->en_programme_name = is_null($this->title_en) ? '' : trim($this->title_en);
		$new_data['programme']->casts = $this->add_cast_field(-1);
		//cast/crew list
		$cast_role = new cast_role();
		$cast_role_list = $cast_role->findByInSql($new_data['programme']->highlighted_cast_roles, AC::ROLE_TYPE_CAST);
		$cast_role_id = array();
		foreach ($cast_role_list as $cast)
		{
			$cast_role_id[] = $cast->id;
		}
		//crew role list
		$crew_role_list = $cast_role->findByInSql($new_data['programme']->highlighted_cast_roles, AC::ROLE_TYPE_CREW);
		$crew_role_id = array();
		foreach ($crew_role_list as $crew)
		{
			$crew_role_id[] = $crew->id;
		}
		$cast_list = array();
		$crew_list = array();
		$json_cast_list = json_decode($new_data['programme']->casts,true);
		if (!empty($json_cast_list))
		{
			foreach ($json_cast_list as $role_id=>$list)
			{
				if (in_array($role_id, $cast_role_id))
				{
					$cast_list[$role_id] = $list;
				}
				elseif (in_array($role_id, $crew_role_id))
				{
					$crew_list[$role_id] = $list;
				}
			}
		}
		else
		{
			$cast_list = array();
			$crew_list = array();
		}
		$old_data['cast_list'] = $cast_list;
		$old_data['crew_list'] = $crew_list;
		//retian input date/time
		if (is_array($this->first_time_onair))
		{
			$this->first_time_onair = implode(' ', $this->first_time_onair);
		}
		$new_data['programme']->first_time_onair = CommonUtils::formatDate($this->first_time_onair);
		if (is_array($this->expire_datetime))
		{
			$this->expire_datetime = implode(' ', $this->expire_datetime);
		}
		$new_data['programme']->expire_datetime  = CommonUtils::formatDate($this->expire_datetime);
		if (is_array($this->publish_datetime))
		{
			$this->publish_datetime = implode(' ', $this->publish_datetime);
		}
		$new_data['programme']->publish_datetime = CommonUtils::formatDate($this->publish_datetime);
		if (is_array($this->first_episode_time_onair))
		{
			$this->first_episode_time_onair = implode(' ', $this->first_episode_time_onair);
		}
		$new_data['programme']->first_episode_time_onair = CommonUtils::formatDate($this->first_episode_time_onair);
		if (is_array($this->last_episode_time_onair))
		{
			$this->last_episode_time_onair = implode(' ', $this->last_episode_time_onair);
		}
		$new_data['programme']->last_episode_time_onair = CommonUtils::formatDate($this->last_episode_time_onair);
		
		$new_data['programme']->programme_language[1]->description = $this->description[1];
		$new_data['programme']->programme_language[2]->description = $this->description[2];

		$new_data['programme']->programme_language[1]->description_short = $this->description_short[1];
		$new_data['programme']->programme_language[2]->description_short = $this->description_short[2];
		
// bug 3978        
		$new_data['programme']->programme_language[1]->first_onair_information = $this->first_onair_information[1];
		$new_data['programme']->programme_language[2]->first_onair_information = $this->first_onair_information[2];
		$new_data['programme']->auto_publish_starttime = CommonUtils::formatDate($this->auto_publish_start_datetime);
		$new_data['programme']->auto_publish_endtime = CommonUtils::formatDate($this->auto_publish_end_datetime);
		$old_data['programme'] = $new_data['programme'];

		//retain input network code
		$network_code_list = array();
		$network_code = new network_code();
		$code_list = $network_code->getCodeByLang(language::getLanguageID(AC::DEFAULT_LANGUAGE));
		if (!empty($code_list))
		{
			foreach ($code_list as $code)
			{
				$checked = (!empty($this->first_network_codes) && in_array($code->code,$this->first_network_codes)) ? 1 : 0;
				$network_code_list[] = array('value'=>$code->code,'label'=>$code->title, 'checked'=>$checked);
			}
		}
		$old_data['code_list'] = $network_code_list;

		//retain nature tag
		$tag_list = array();
		$tag = new tag();
		if (!empty($this->tag))
		{
			foreach ($this->tag as $type_id=>$tags)
			{
				foreach ($tags as $tag_id)
				{
					$tag_detail = $tag->get($tag_id);
					$tag_list[$type_id][] = array("id"=>$tag_detail->id,"system_label"=>$tag_detail->system_label);
				}
			}
		}
		$old_data['tag_list'] = $tag_list;

        //retain cpl data
        $cpl_list = array();
        if ($this->cpl_id && $this->cpl_company_code && $this->effective_date)
        {
            $num = count($this->cpl_id);
            for ($i=0; $i<$num; $i++)
            {
                $programme_cpl = new programme_cpl();
                $programme_cpl->programme_id = $this->id;
                $programme_cpl->effective_date = $this->effective_date[$i];
                $programme_cpl->cpl_id = urldecode(trim($this->cpl_id[$i]));
                $programme_cpl->cpl_company_code = $this->cpl_company_code[$i];
                $cpl_list[$i] = $programme_cpl;
            }
        }
        $old_data['cpl_list'] = $cpl_list;

		//retail programme category
		$tvb_category_arr = array();
		$programme_tvbcom_category = new programme_tvbcom_category();		
		if (!empty($this->tvbcom_cat_id))
		{
			$this->tvbcom_cat_id = array_unique($this->tvbcom_cat_id);
			foreach ($this->tvbcom_cat_id as $id)
			{
				$tvbcom_category_object = new tvbcom_category();
				$tvbcom_category = $tvbcom_category_object->get($id);
				$parent_name = tvbcom_category::getParentName($tvbcom_category->system_label, $tvbcom_category->parent_id);
				$tvb_category_arr[] = array("id"=>$tvbcom_category->id, "system_label"=>$parent_name." ".$tvbcom_category->system_label);
			}
		}
		$old_data['tvb_category_list'] = $tvb_category_arr;

		//retail programme category
		$category_list = array();
		if(!empty($this->cpl_category_id))
		{
			$cpl_category = new cpl_category();

			$category_detail = $cpl_category->getCategoryByID($this->cpl_category_id);
			$category_list[0] = 'Please Select...'; 
			$sub_categorys = $cpl_category->getSubCategorys($category_detail[0]->parent_id);
			foreach ($sub_categorys as $cat_id => $cat_name)
			{
				$category_list[$cat_id] = $cat_name;
			}
			$old_data['category_detail'] = $category_detail[0];
		}
		elseif(!empty($this->parent_cpl_category))
		{
			$cpl_category = new cpl_category();
			$category_detail->parent_id = $this->parent_cpl_category;
			$category_detail->id = '';
			$sub_categorys = $cpl_category->getSubCategorys($this->parent_cpl_category);
			$category_list[0] = 'Please Select...'; 
			foreach ($sub_categorys as $cat_id => $cat_name)
			{
				$category_list[$cat_id] = $cat_name;
			}
			$old_data['category_detail'] = $category_detail;
		}
		else
		{
			$category_detail->parent_id = '';
			$category_detail->id = '';
			$category_list[0] = 'Please Select...';
			$old_data['category_detail'] = $category_detail;
		}
		$old_data['category_list'] = $category_list;

		foreach ($old_data as $object=>$data)
		{
			$this->setData($object, $data);
		}

		//jump page
		$this->setData('id', $this->id);
		$this->setData('from', $this->from);
		$this->setData('type', 'programme');
		$this->setData('act', $this->act);
		$this->setData('step', 2);

        $this->__init_country();
        $this->__init_programme_subscription();
        $this->__init_programme_ppv();
        $this->__init_programme_premium();
	}

    private function __init_country()
    {
 		$country = new country();
        $this->setData('country', $country->getCountryList());
    }

    private function __init_programme_premium()
    {
        $premium = array();
        if($this->premium_flag)
        {
            $premium['premium_auto_publish'] = $this->premium_auto_publish;
        }
		$premium['premium_title'] = $this->premium_title;
		$premium['premium_title_en'] = $this->premium_title_en;
		$premium['premium_items']['subscription'] = !empty($this->premium_items) && in_array('subscription',$this->premium_items) ? 1 :0;
		$premium['premium_items']['ppv'] = !empty($this->premium_items) && in_array('ppv',$this->premium_items) ? 1 :0;
        $this->setData('programme_premium', $premium);
    }

    private function __init_programme_ppv()
    {
        $ppv = array();
        $ppv['publish_datetime'] = isset($this->ppv_publish_datetime) ? $this->ppv_publish_datetime : '';
        $ppv['expire_datetime'] = isset($this->ppv_expire_datetime) ? $this->ppv_expire_datetime : '';
        $ppv['ppv_country'] = $this->ppv_country;
        $ppv['ppv_country_allow_deny'] = $this->ppv_country_allow_deny;
        $this->setData('programme_ppv', $ppv);
    }

    private function __init_programme_subscription()
    {
        $subscription = array();
        $subscription['publish_datetime'] = $this->subscription_publish_datetime;
        $subscription['expire_datetime'] = $this->subscription_expire_datetime;
        $subscription['free'] = $this->subscription_free;
        $subscription['subscription_country'] = $this->subscription_country;
        $subscription['subscription_country_allow_deny'] = $this->subscription_country_allow_deny;
        $this->setData('programme_subscription', $subscription);
    }

    private function __check_subscription_datetime()
    {
        $flag = true;
        if ($this->subscription_publish_datetime && $this->subscription_expire_datetime) {
            if ($this->subscription_publish_datetime > $this->subscription_expire_datetime) {
                $this->addError('Online Date Time / Offline Date Time', array('0205', 'Subscription Online Date Time / Offline Date Time'));
                $flag = FALSE;
            }
        }
        else
        {
            $this->addError('Online Date Time / Offline Date Time', array('0402', 'Subscription Online Date Time / Offline Date Time'));
            $flag =  false; 
        }
        return $flag;
    }

    private function __check_ppv_datetime()
    {
        $flag = true;
        if (!empty($this->ppv_publish_datetime) && !empty($this->ppv_expire_datetime)) {
            if ($this->ppv_publish_datetime > $this->ppv_expire_datetime) {
                $this->addError('Online Date Time / Offline Date Time', array('0205', 'Pay-Per-View Online Date Time / Offline Date Time'));
                $flag =  FALSE;
            }
        }
        else
        {
            $this->addError('Online Date Time / Offline Date Time', array('0402', 'Pay-Per-View Online Date Time / Offline Date Time'));
            $flag =  false; 
        }
        return $flag;
    }

    //bug 3978    
    private function _checkFirstAirDatetime()
    {
        if (!empty($this->first_time_onair)) {
            return $this->first_time_onair == $this->first_episode_time_onair;
        } else {
            $this->first_time_onair = $this->first_episode_time_onair;
            return TRUE;
        }
    }

    //bug 4672
    private function deleteVideoPremium($programme_id)
    {
        $sql = 'select * from video where programme_id = :id';
        $videos = Model::selectBySql($sql,array(':id'=>$programme_id));
        $video_obj = new video();
        if(!empty($videos))
        {
            foreach($videos as $video)
            {
                $a = Model::$dbo['w']->delete('video_premium','video_id=?',array($video['id']));
                $b = Model::$dbo['w']->delete('video_ppv','video_id=?',array($video['id']));
                $c = Model::$dbo['w']->delete('video_subscription','video_id=?',array($video['id']));

				$a && $this->change_log[] = array(
					'type'=>'video_premium',
					'keys'=>array('video_id'=>$video['id']),
					'is_active' => 0,
					'is_publish'=> 0,
					'programme_id'=>$programme_id
				);
				$b && $this->change_log[] = array(
					'type'=>'video_ppv',
					'keys'=>array('video_id'=>$video['id']),
					'is_active' => 0,
					'is_publish'=> 0,
					'programme_id'=>$programme_id
				);
				$c && $this->change_log[] = array(
					'type'=>'video_subscription',
					'keys'=>array('video_id'=>$video['id']),
					'is_active' => 0,
					'is_publish'=> 0,
					'programme_id'=>$programme_id
				);

                //update video premium flag
                $_video = $video_obj->get($video['id']);
                $_video->premium_flag = 0;
		        Model::$dbo['w']->save($_video);
            }
        }
    }

	private function __checkAutoPublishTime()
	{
		if ($this->auto_publish) {
			if (empty($this->auto_publish_start_datetime) || empty($this->auto_publish_end_datetime) || ($this->auto_publish_start_datetime > $this->auto_publish_end_datetime)) {
  			    $this->addError('Auto Publish Online Date Time / Offline Date Time', array('0205', 'Auto Publish Online Date Time / Offline Date Time'));
                $this->init_page_data();
				return FALSE;
			}
		} 
	}
}
?>
